var prefix = jsctx + "/tenantTicketType";

var tenantTicketType = (function () {
    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
        load();
    };

    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };
    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listTenantTicketType",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: true,
                singleSelect: false,
                pageSize: 20,
                pageList: [10, 20, 30],
                pageNumber: 1,
                sidePagination: "server",
                cache: false,
                paginationShowPageGo: true,
                height: h,
                queryParams: function (params) {
                    return {
                        limit: params.limit,
                        offset: (params.offset / params.limit) + 1,
                        ticketName: $("#ticketName").val().trim(),
                        startDate: $("#startDate").val().trim(),
                        endDate: $("#endDate").val().trim(),
                        ticketSuitType: $("#ticketSuitType").val().trim(),
                        availabilityStatus: $("#availabilityStatus").val().trim()
                    };
                },
                columns: [
                    {
                        field: 'number', title: '#', width: '50', align: 'left',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                    {field: 'ticketName', title: '卡券名称', align: 'left', width: '100'},
                    {
                        field: 'ticketSuitType',
                        title: '卡券类型',
                        width: '100', align: 'left',
                        formatter: function (value, row, index) {
                            if (value == '0') {
                                return '充电减免';
                            } else if (value == '1') {
                                return '服务费减免';
                            } else if (value == '2') {
                                return '充电满折';
                            } else if (value == '3') {
                                return '服务费满折';
                            } else if (value == '4') {
                                return '代金券';
                            }
                        }
                    },
                    {
                        field: 'applianceUser', title: '用户类型', width: '100', align: 'left',
                        formatter: function (value, row, index) {
                            if (value == '0') {
                                return '全部用户';
                            } else if (value == '1') {
                                return '新用户';
                            } else if (value == '2') {
                                return '充电满折';
                            } else if (value == '9') {
                                return row.applicnceLevel;
                            } else if (value == '10') {
                                return '企业用户';
                            }
                        }
                    },
                    {
                        field: 'ticketSource', title: '发放方式', width: '100', align: 'left',
                        formatter: function (value, row, index) {
                            if (value == '0') {
                                return '系统推送';
                            } else if (value == '1') {
                                return '主动领取';
                            }
                        }
                    },
                    {field: 'discountDesc', title: '优惠方式', width: '100', align: 'left'},
                    {field: 'sendDate', title: '发放时间', align: 'left', width: '100'},
                    {field: 'effectDateDesc', title: '有限期', align: 'left', width: '120'},
                    {
                        field: 'remainTicket', title: '剩余数量', align: 'left', width: '60',
                        formatter: function (value, row, index) {
                            if (row.isMax == '1') {
                                return '无限制';
                            } else {
                                return value;
                            }
                        }
                    },
                    {
                        field: 'totalTicket', title: '总量', align: 'left', width: '60',
                        formatter: function (value, row, index) {
                            if (row.isMax == '1') {
                                return '无限制';
                            } else {
                                return value;
                            }
                        }
                    },
                    {field: 'createdTime', title: '创建时间', align: 'left', width: '80'},
                    {field: 'statusDesc', title: '状态', width: '100', align: 'center'},
                    {
                        title: '操作',
                        field: 'orderId',
                        width: '200', align: 'center',
                        formatter: function (value, row, index) {
                            // var a = '';
                            // var b = '';
                            // var c = '';
                            // var d = '';
                            // var e = '';
//                             if (OperationsManagement_coupon_look) {
//                                 a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="详情" onclick="tenantTicketType.detialTenantTicketType(\''
//                                     + row.ticketTypeId
//                                     + '\')">详情</a> ';
// /*                                d = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="发放记录" onclick="tenantTicketType.sendRecord(\''
//                                     + row.ticketTypeId
//                                     + '\')">发放记录</a> ';
//                                 e = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="赠送记录" onclick="tenantTicketType.giveRecord(\''
//                                     + row.ticketTypeId
//                                     + '\')">赠送记录</a> ';*/
//                             }
//                             if (OperationsManagement_coupon_update) {
//                                 if (row.status == '0') {
//                                     b = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="停用" onclick="tenantTicketType.updateStatus(\''
//                                         + row.ticketTypeId
//                                         + '\',0)">停用</a> ';
//                                 } else if (row.status == '1') {
//                                     b = '<a class="btn btn-info btn-sm ' + has_edit + '" href="#" title="启动" onclick="tenantTicketType.updateStatus(\''
//                                         + row.ticketTypeId
//                                         + '\',1)">启动</a> ';
//                                 }
//                                 c = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" title="发放优惠券" onclick="tenantTicketType.giveAway(\''
//                                     + row.ticketTypeId
//                                     + '\')">发放优惠券</a> ';
//                             }

                            var a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="详情" onclick="tenantTicketType.detail(\''
                                    + row.ticketTypeId + '\')">详情</a> ';
                            var b = '<a class="btn btn-warning btn-sm ' + has_edit + '" href="#" title="编辑" onclick="tenantTicketType.edit(\''
                                + row.ticketTypeId + '\')">编辑</a> ';
                            var c = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="作废" onclick="tenantTicketType.updateTicketForChangeStatus(\''
                                + row.ticketTypeId + '\',1)">作废</a> ';
                            var d = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="删除" onclick="tenantTicketType.delete(\''
                                + row.ticketTypeId + '\')">删除</a> ';
                            var operator = a;
                            if (row.statusDesc == '未开始' ) {
                                operator = operator + b + d;
                            } else if (row.statusDesc == '发放中') {
                                operator = operator + b + c;
                            } else if (row.statusDesc == '已作废') {
                                operator = operator + b + d;
                            }
                            return operator;







                        }
                    }
                ]
            });
    };

    function addTenantTicketType() {
        location.href = prefix + "/addTenantTicketType";
    }

    function giveAway(ticketTypeId) {
        location.href = prefix + "/giveAway/" + ticketTypeId;
    }

    function timeingGiveAway(ticketTypeId) {
        location.href = prefix + "/timeingGiveAway/" + ticketTypeId;
    }

    function updateStatus(ticketTypeId, type) {
        if (type == 0) {
            //核实数据是对商品启用
            $.ajax({
                url: jsctx + "/shopGoods/selectByTicketTypeId",
                type: "get",
                data: {
                    'ticketTypeId': ticketTypeId
                },
                success: function (data) {
                    if (data.status == 200) {
                        updataStatusWithShopGood(ticketTypeId)
                    } else {
                        updataStatusButton(ticketTypeId);
                    }
                }
            });
        } else {
            updataStatusButton(ticketTypeId);
        }
    }

    function updataStatusWithShopGood(ticketTypeId) {
        layer.confirm('此优惠券有相关联的积分商城商品正在进行中，如果停用则商品自动下架。是否继续？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateStatus",
                type: "post",
                data: {
                    'ticketTypeId': ticketTypeId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function updataStatusButton(ticketTypeId) {
        layer.confirm('确定要变更状态？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateStatus",
                type: "post",
                data: {
                    'ticketTypeId': ticketTypeId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    function giveRecord(ticketTypeId) {
        location.href = prefix + "/giveRecord/" + ticketTypeId;
    }

    function getRecord(ticketTypeId) {
        location.href = prefix + "/getRecord/" + ticketTypeId;
    }

    function detail(ticketTypeId) {
        location.href = prefix + "/detail/" + ticketTypeId;
    }

    function edit(ticketTypeId) {
        location.href = prefix + "/edit/" + ticketTypeId;
    }

    function deleteTicket(ticketTypeId) {
        layer.confirm('确定要删除选中的记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/delete",
                type: "post",
                data: {
                    'id': ticketTypeId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        });
    }

    function updateTicketForChangeStatus(ticketTypeId, status) {
        layer.confirm('确定要作废该记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateTicketForChangeStatus",
                type: "post",
                data: {
                    'id': ticketTypeId,
                    'status': status
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        });
    }

    function sendRecord(ticketTypeId) {
        location.href = prefix + "/sendRecord/" + ticketTypeId;
    }

    function exportInfo() {
        $.fileDownload(prefix + "/exporListTenantTicketType", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text(),

                ticketName: $("#ticketName").val().trim(),
                startDate: $("#startDate").val().trim(),
                endDate: $("#endDate").val().trim(),
                ticketSuitType: $("#ticketSuitType").val().trim(),
                availabilityStatus: $("#availabilityStatus").val().trim()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    };

    return {
        init: init,
        reLoad: reLoad,
        updateStatus: updateStatus,
        addTenantTicketType: addTenantTicketType,
        giveAway: giveAway,
        timeingGiveAway: timeingGiveAway,
        getRecord: getRecord,
        giveRecord: giveRecord,
        detail: detail,
        edit:edit,
        delete:deleteTicket,
        updateTicketForChangeStatus:updateTicketForChangeStatus,
        sendRecord: sendRecord,
        exportInfo: exportInfo
    };
})();



var addTenantTicketType = (function () {
        function init() {
            $("input[name='discountAmount']").blur(function () {
                if ($(this).val()) {
                    $(".couponError").remove()
                }
            })
            $("input[name='discount']").blur(function () {
                if ($(this).val()) {
                    $(".couponError").remove()
                }
            })

            validateRule();

            layui.use(['form'], function () {
                var form = layui.form;
                form.render();
            });
        };



        function save() {

            var stationIds = [];
            $(".elecStationId:checked").each(function () {
                stationIds.push($(this).val())
            })
            var stationIds = [];
            $(".elecStationId:checked").each(function () {
                stationIds.push($(this).val())
            })
            $("input[name='layuiTreeCheck']:checked").each(function () {
                if ($(this).val() != "undefined") {
                    stationIds.push($(this).val())
                }
            })


            if ($("input[name='discountType']:checked").val() == "0" && $("input[name='discountAmount']").val() == "") {
                var str = `<label id="ticketName-error" class="error couponError" ><i class="fa fa-times-circle"></i> 请输入立减</label>`
                $("input[name='discountAmount']").after(str)
                return;
            }
            if ($("input[name='discountType']:checked").val() == "1" && $("input[name='discount']").val() == "") {
                var str = `<label id="ticketName-error" class="error couponError" ><i class="fa fa-times-circle"></i> 请输入打折</label>`
                $("input[name='discount']").after(str)
                return;
            }
            if ($("input[name='effectType']:checked").val() == "0" && $("input[name='effectDay']").val() == "") {
                var str = `<label id="ticketName-error" class="error couponError" ><i class="fa fa-times-circle"></i> 请输入有效期</label>`
                $("input[name='effectDay']").after(str)
                return;
            }
            if ($("input[name='effectType']:checked").val() == "1" && $("input[name='effectStartDate']").val() == "") {
                var str = `<label id="ticketName-error" class="error couponError" ><i class="fa fa-times-circle"></i> 请选择时间</label>`
                $("input[name='effectStartDate']").after(str)
                return;
            }
            if ($("input[name='effectType']:checked").val() == "1" && $("input[name='effectEndDate']").val() == "") {
                var str = `<label id="ticketName-error" class="error couponError" ><i class="fa fa-times-circle"></i> 请选择时间</label>`
                $("input[name='effectEndDate']").after(str)
                return;
            }

            var formData = new FormData($("#frmTenantTicketType")[0]);
            if($("#applianceUser").val()=='10'){
                formData.append("levels",$("#enterpirseId").val())
                //$("input[name='applicnceLevel']").after($("#enterpirseId").val());
            }else{
                formData.append("levels",$("#applicnceLevel").val())
                //$("input[name='applicnceLevel']").after($("#userId").val());
            }
            formData.append("stationIds", stationIds),
                console.warn(formData.get("stationIds"))
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveOrUpdateTenantTicketType",
                data: formData,
                processData: false,
                contentType: false,
                // async: false,
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        parent.layer.alert(data.message)
                    }

                }
            });
        }

        function validateRule() {
            var icon = "<i class='fa fa-times-circle'></i> ";
            $("#frmTenantTicketType").validate({
                rules: {
                    ticketName: {
                        required: true
                    },
                    useRequireAmount: {
                        required: true,
                        number: true,
                        min: 0,
                    },
                    effectDay: {
                        required: true,
                        digits: true,
                        min: 0
                    },
                    discountAmount: {
                        required: true,
                        number: true,
                        min: 0
                    },
                    discount: {
                        number: true,
                        min: 0,
                        max: 1
                    },
                    totalTicket: {
                        digits: true,
                        min: 1,
                        maxlength: 9
                    }, remark: {
                        maxlength: 450
                    },totalTicket:{
                        required: true
                    },ticketUnitCount:{
                        required: true
                    }
                },
                messages: {
                    ticketName: {
                        required: icon + "请输入优惠券名称"
                    }
                    ,
                    useRequireAmount: {
                        required: icon + "请输入使用条件",
                        number: icon + "请输入大于等于0的数字",
                        min: icon + "请输入大于等于0的数字",
                    }
                    ,
                    effectDay: {
                        required: icon + "请输入有效期",
                        digits: icon + "请输入大于0的正整数字",
                        min: icon + "请输入大于0的正整数字"
                    }
                    ,
                    discountAmount: {
                        required: icon + "请输入优惠立减金额",
                        number: icon + "请输入大于0的正整数字",
                        min: icon + "请输入大于0的正整数字"
                    },
                    discount: {
                        number: icon + "请输入有效数字",
                        min: icon + "请输入大于0的数字",
                        max: icon + "请输入小于1的数字"
                    }
                    ,
                    totalTicket: {
                        digits: icon + "请输入大于0的正整数字",
                        min: icon + "请输入大于0的正整数字",
                        maxlength: icon + "请输入小于9位数",
                    }, remark: {
                        maxlength: icon + "请输入小于450字",
                    },totalTicket:{
                        required: icon + "请输入发放总数"
                    },ticketUnitCount:{
                        required: icon + "请输入领取次数"
                    }
                }
                ,
                submitHandler: function (form) {
                    save();
                }
            })
        }





        layui.use(['form', 'jquery', 'tree', 'util'], function () {
            var form = layui.form;
            var $ = layui.jquery;
            var tree = layui.tree;
            var util = layui.util;
            //点击全选, 勾选---自营
            form.on('checkbox(self_allChoose)', function (data) {
                var child = $(".self_seach input[type='checkbox']");
                child.each(function (index, item) {
                    item.checked = data.elem.checked;
                });
                form.render('checkbox');
            });
            //点击全选, 勾选---非自营
            form.on('checkbox(unSelf_allChoose)', function (data) {
                var child = $(".unSelf_seach input[type='checkbox']");
                child.each(function (index, item) {
                    item.checked = data.elem.checked;
                });
                form.render('checkbox');
            });
            //点击全选, 勾选---外部互联互通
            form.on('checkbox(connectivity_checkall)', function (data) {
                var child = $(".connectivity_seach input[type='checkbox']");
                child.each(function (index, item) {
                    item.checked = data.elem.checked;
                });
                form.render('checkbox');
            });
            //点击全选, 勾选---内部互联互通
            form.on('checkbox(connectivity_inner_checkall)', function (data) {
                var child = $(".connectivity_inner_seach input[type='checkbox']");
                child.each(function (index, item) {
                    item.checked = data.elem.checked;
                });
                form.render('checkbox');
            });
            //---自营Li
            form.on("checkbox(self_list)", function (data) {
                $(".self_seach input[type='checkbox']").each(function () {
                    if ($(".self_seach input[type='checkbox']:checked").length == $(".self_seach input[type='checkbox']").length) {
                        $('#self_checkall').prop("checked", true)
                    } else {
                        $('#self_checkall').prop("checked", false)
                    }
                })
                form.render('checkbox');
            });
            //---非自营Li
            form.on("checkbox(unSelf_list)", function (data) {
                $(".unSelf_seach input[type='checkbox']").each(function () {
                    if ($(".unSelf_seach input[type='checkbox']:checked").length == $(".unSelf_seach input[type='checkbox']").length) {
                        $('#unSelf_checkall').prop("checked", true)
                    } else {
                        $('#unSelf_checkall').prop("checked", false)
                    }
                })
                form.render('checkbox');
            });
            // //---互联互通外部Li
            // form.on("checkbox(connectivity_list)", function (data) {
            //     $(".connectivity_seach input[type='checkbox']").each(function () {
            //         if ($(".connectivity_seach input[type='checkbox']:checked").length == $(".connectivity_seach input[type='checkbox']").length) {
            //             $('#connectivity_checkall').prop("checked", true)
            //         } else {
            //             $('#connectivity_checkall').prop("checked", false)
            //         }
            //     })
            //     form.render('checkbox');
            // });

            //打折与立减切换
            form.on("radio(discountType)", function (data) {
                if ($(this).val() == "0") {
                    $(".reductionDiv").removeClass("hide");
                    $(".discountDiv").addClass("hide");
                } else {
                    $(".reductionDiv").addClass("hide");
                    $(".discountDiv").removeClass("hide");
                }
            });
            //获取后和在日期切换
            form.on("radio(effectType)", function (data) {
                if ($(this).val() == "0") {
                    $(".gainDiv").removeClass("hide");
                    $(".dateDiv").addClass("hide");
                } else {
                    $(".gainDiv").addClass("hide");
                    $(".dateDiv").removeClass("hide");
                }
            });

            //获取互联互通内部桩群
            function listTicketStationHlht() {
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: prefix + "/listTicketStationHlht",
                    data: {
                        "ticketTypeId": $("#ticketTypeId").val()
                    },
                    // processData: false,
                    // contentType: false,
                    // async: false,
                    error: function (request) {
                        parent.layer.alert("Connection error");
                    },
                    success: function (data) {
                        console.log(data)
                        var dataList = [];
                        for (var key in data.data) {
                            var obj = {
                                title: (data.data[key])[0].tenantName
                                , id: 'undefined'
                                , field: 'tenantName'
                                , checked: false
                                , spread: false
                                , children: data.data[key].map(function (ele) {
                                    var childrenObj = {}
                                    childrenObj.title = ele.stationName;
                                    childrenObj.id = ele.elecStationId;
                                    childrenObj.checked = false;
                                    childrenObj.spread = false;
                                    return childrenObj
                                })
                            }
                            dataList.push(obj)
                        }
                        //树形组件
                        tree.render({
                            elem: '#connectivity_inner_seach_tree'
                            , data: dataList
                            , showCheckbox: true  //是否显示复选框
                            , id: 'demoId1'
                            , showLine: true
                            , isJump: false //是否允许点击节点时弹出新窗口跳转
                            , click: function (obj) {
                                // var data = obj.data;  //获取当前点击的节点数据
                                // layer.msg('状态：'+ obj.state + '<br>节点数据：' + JSON.stringify(data));
                                console.log(obj.data)
                            }
                        });
                    }
                });
            }

            //获取互联互通外部桩群
            function listTicketStationExternalHlht() {
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: prefix + "/listTicketStationExternalHlht",
                    data: {
                        "ticketTypeId": $("#ticketTypeId").val()
                    },
                    // processData: false,
                    // contentType: false,
                    // async: false,
                    error: function (request) {
                        parent.layer.alert("Connection error");
                    },
                    success: function (data) {
                        console.log(data)
                        var dataList = [];
                        for (var key in data.data) {
                            var obj = {
                                title: key
                                , id: 'undefined'
                                , field: 'tenantName'
                                , checked: false
                                , spread: false
                                , children: data.data[key].map(function (ele) {
                                    var childrenObj = {}
                                    childrenObj.title = ele.stationName;
                                    childrenObj.id = ele.elecStationId;
                                    childrenObj.checked = false;
                                    childrenObj.spread = false;
                                    return childrenObj
                                })
                            }
                            dataList.push(obj)
                        }
                        //树形组件
                        tree.render({
                            elem: '#connectivity_seach_tree'
                            , data: dataList
                            , showCheckbox: true  //是否显示复选框
                            , id: 'demoId1'
                            , showLine: true
                            , isJump: false //是否允许点击节点时弹出新窗口跳转
                            , click: function (obj) {
                                // var data = obj.data;  //获取当前点击的节点数据
                                // layer.msg('状态：'+ obj.state + '<br>节点数据：' + JSON.stringify(data));
                                console.log(obj.data)
                            }
                        });
                    }
                });
            }

            listTicketStationHlht();
            listTicketStationExternalHlht();
        });


        return {
            init: init
        };
    }

)();


var giveAway = (function () {

    /*------  验证码  -----*/
    var num1 = 60;
    var ajaxReady = true;

    function getTicketAuthCode() {
        if (ajaxReady) {
            $.ajax({
                url: prefix + "/getTicketAuthCode",
                type: "POST",
                data: {},
                beforeSend: function () {
                    ajaxReady = false;
                },
                success: function (data) {
                    if (data.status == 200) {
                        time();

                        function time() {
                            if (num1 == 0) {
                                $('#verificationCode').attr("disabled", "disabled")
                                $('#sendVerificationCode').text("获取验证码");
                                $('#sendVerificationCode').attr("onclick", 'giveAway.getTicketAuthCode()');
                                ajaxReady = true;
                                num1 = 60;
                            } else {
                                $('#verificationCode').removeAttr('disabled')
                                $('#sendVerificationCode').html(num1 + "秒后重试");
                                $('#sendVerificationCode').removeAttr('onclick');
                                num1--;
                                setTimeout(function () {
                                    time()
                                }, 1000)
                            }
                        }
                    } else {
                        parent.layer.alert(data.message);
                        ajaxReady = true;
                    }

                }
            })


        }
    }


    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    var isajaxsend = true;

    function save() {
        if (isajaxsend) {

            if ($("input[name='userType']:checked").val() == "0" && $("textarea[name='members']").val() == "") {
                var str = `<label id="ticketName-error" class="error couponError" ><i class="fa fa-times-circle"></i> 请输入用户手机号</label>`
                $("textarea[name='members']").after(str)
                return;
            }
            if ($("input[name='sendType']:checked").val() == "0" && $("input[name='sendCount']").val() == "") {
                var str = `<label id="ticketName-error" class="error couponError" ><i class="fa fa-times-circle"></i> 请输入赠送数量</label>`
                $("input[name='sendCount']").after(str)
                return;
            }
            if ($("input[name='sendType']:checked").val() == "1" && $("input[name='ticketScheduleCount']").val() == "") {
                var str = `<label id="ticketName-error" class="error couponError" ><i class="fa fa-times-circle"></i> 请输入发送频率</label>`
                $("input[name='ticketScheduleCount']").after(str)
                return;
            }
            if ($("input[name='sendType']:checked").val() == "1" && $("input[name='sendNum']").val() == "") {
                var str = `<label id="ticketName-error" class="error couponError" ><i class="fa fa-times-circle"></i> 请输入发送数量</label>`
                $("input[name='sendNum']").after(str)
                return;
            }
            if ($("input[name='sendType']:checked").val() == "1" && $("input[name='firstSendTime']").val() == "") {
                var str = `<label id="ticketName-error" class="error couponError" ><i class="fa fa-times-circle"></i> 请输入首次赠送时间</label>`
                $("input[name='firstSendTime']").after(str)
                return;
            }


            var formData = new FormData($("#frmGiveAway")[0]);
            $("#roleIds").val(getCheckedRoles());
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveGiveAway",
                data: formData,
                processData: false,
                contentType: false,
                // async: false,
                beforeSend: function () {
                    isajaxsend = false
                },
                error: function (data) {
                    isajaxsend = true
                    parent.layer.alert(data.message);
                },
                success: function (data) {
                    if (data.status == 200) {
                        isajaxsend = false
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        isajaxsend = true
                        parent.layer.alert(data.message)
                    }

                },
                complete: function () {
                    isajaxsend = false
                }
            });
        }
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmGiveAway").validate({
            rules: {
                sendCount: {
                    digits: true,
                    min: 0
                },
                ticketScheduleCount: {
                    digits: true,
                    min: 0
                },
                sendNum: {
                    digits: true,
                    min: 0
                },
                verificationCode: {
                    required: true,
                }

            },
            messages: {
                sendCount: {
                    digits: icon + "请输入大于0的正整数",
                    min: icon + "请输入大于0的正整数"
                },
                ticketScheduleCount: {
                    digits: icon + "请输入大于0的正整数",
                    min: icon + "请输入大于0的正整数"
                },
                sendNum: {
                    digits: icon + "请输入大于0的正整数",
                    min: icon + "请输入大于0的正整数"
                },
                verificationCode: {
                    required: icon + "请输入验证码"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init,
        getTicketAuthCode: getTicketAuthCode
    };
})();

